/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ExJoUpdate.java
 *
 * Created on 01/12/2011, 02:08:41
 */
package proj5labbd.graphics.exibicaoJornal;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import proj5labbd.DBInterface;
import proj5labbd.graphics.abstractOpGraphics.OperationPanel;

public class ExJoUpPanel extends OperationPanel {

    /** Creates new form ExJoUpdate */
    public ExJoUpPanel(ExJoFrame frame, DBInterface dbInterface) {
        super(frame, dbInterface);
        initComponents();
        jbtUpdate.addActionListener(new ExJoAction());
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jpnParam = new javax.swing.JPanel();
        jlbData = new javax.swing.JLabel();
        jlbHoraIn = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jtbJornal = new javax.swing.JTable();
        jlbJornal = new javax.swing.JLabel();
        jlbFuncionario = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jtbFuncionario = new javax.swing.JTable();
        jLabel1 = new javax.swing.JLabel();
        jlbIbope = new javax.swing.JLabel();
        jtxtIbope = new javax.swing.JTextField();
        jftxtDate = new javax.swing.JFormattedTextField();
        jftxtIni = new javax.swing.JFormattedTextField();
        jftxtFim = new javax.swing.JFormattedTextField();
        jScrollPane5 = new javax.swing.JScrollPane();
        jtbUpdate = new javax.swing.JTable();
        jbtUpdate = new javax.swing.JButton();

        setBorder(javax.swing.BorderFactory.createTitledBorder("Atualização"));
        addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentShown(java.awt.event.ComponentEvent evt) {
                formComponentShown(evt);
            }
        });

        jpnParam.setBorder(javax.swing.BorderFactory.createTitledBorder("Parâmetros de atualização"));

        jlbData.setText("Data");

        jlbHoraIn.setText("Hora de início");

        jtbJornal.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        jtbJornal.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jScrollPane1.setViewportView(jtbJornal);

        jlbJornal.setText("Jornal");

        jlbFuncionario.setText("Apresentador");

        jtbFuncionario.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        jtbFuncionario.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jScrollPane2.setViewportView(jtbFuncionario);

        jLabel1.setText("Hora de término");

        jlbIbope.setText("Ibope");

        try {
            jftxtDate.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##-##-####")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        jftxtDate.setFocusLostBehavior(javax.swing.JFormattedTextField.COMMIT);

        try {
            jftxtIni.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##:##")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        jftxtIni.setFocusLostBehavior(javax.swing.JFormattedTextField.COMMIT);

        try {
            jftxtFim.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##:##")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        jftxtFim.setFocusLostBehavior(javax.swing.JFormattedTextField.COMMIT);

        javax.swing.GroupLayout jpnParamLayout = new javax.swing.GroupLayout(jpnParam);
        jpnParam.setLayout(jpnParamLayout);
        jpnParamLayout.setHorizontalGroup(
            jpnParamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpnParamLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jpnParamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 405, Short.MAX_VALUE)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 405, Short.MAX_VALUE)
                    .addComponent(jlbJornal)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jpnParamLayout.createSequentialGroup()
                        .addGroup(jpnParamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jlbData, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jftxtDate, javax.swing.GroupLayout.PREFERRED_SIZE, 124, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jpnParamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jftxtIni)
                            .addComponent(jlbHoraIn, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jpnParamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jftxtFim)
                            .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jpnParamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jtxtIbope, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jlbIbope, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                    .addComponent(jlbFuncionario))
                .addContainerGap())
        );
        jpnParamLayout.setVerticalGroup(
            jpnParamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpnParamLayout.createSequentialGroup()
                .addGroup(jpnParamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jlbData)
                    .addComponent(jLabel1)
                    .addComponent(jlbIbope)
                    .addComponent(jlbHoraIn))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jpnParamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jtxtIbope, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jftxtDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jftxtIni, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jftxtFim, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jlbJornal)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 126, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jlbFuncionario)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 204, Short.MAX_VALUE)
                .addContainerGap())
        );

        jtbUpdate.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        jScrollPane5.setViewportView(jtbUpdate);

        jbtUpdate.setText("Atualizar");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jpnParam, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addContainerGap())
                    .addComponent(jScrollPane5, javax.swing.GroupLayout.DEFAULT_SIZE, 453, Short.MAX_VALUE)
                    .addComponent(jbtUpdate, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addComponent(jpnParam, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane5, javax.swing.GroupLayout.PREFERRED_SIZE, 179, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(30, 30, 30)
                .addComponent(jbtUpdate))
        );
    }// </editor-fold>//GEN-END:initComponents

    /*
     * Resgata as informações das tabelas que serão exibidas
     */
    private void formComponentShown(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentShown
        // TODO add your handling code here:
        try {
            // TODO add your handling code here:
            setupTable();
        } catch (SQLException ex) {
            frame.printException(ex);
            JOptionPane.showMessageDialog(null, "Não foi possível resgatar os dados das tabelas");
        }
    }//GEN-LAST:event_formComponentShown

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane5;
    private javax.swing.JButton jbtUpdate;
    private javax.swing.JFormattedTextField jftxtDate;
    private javax.swing.JFormattedTextField jftxtFim;
    private javax.swing.JFormattedTextField jftxtIni;
    private javax.swing.JLabel jlbData;
    private javax.swing.JLabel jlbFuncionario;
    private javax.swing.JLabel jlbHoraIn;
    private javax.swing.JLabel jlbIbope;
    private javax.swing.JLabel jlbJornal;
    private javax.swing.JPanel jpnParam;
    private javax.swing.JTable jtbFuncionario;
    private javax.swing.JTable jtbJornal;
    private javax.swing.JTable jtbUpdate;
    private javax.swing.JTextField jtxtIbope;
    // End of variables declaration//GEN-END:variables

    /*
     * Formata as tabelas: jornal, funcionario e exibicaoJornal
     */
private void setupTable() throws SQLException {
        
        String [] titlesJo = {"ID Jornal","Titulo","Descrição","ID Departamento",
            "Duração","Abrangência"};
        String [] fieldsJo = {"jornal.idPr","jornal.tituloPr","jornal.descricaoPr",
            "jornal.idDe","jornal.duracaoJo","jornal.abrangenciaJo"};
        String [] paramsJo = {"jornal.idDe=departamento.idDe"};
        String [][] sJo = dbInterface.view(fieldsJo, paramsJo, new String[]{"jornal","departamento"});
        
        DefaultTableModel model = new DefaultTableModel(sJo,titlesJo);
        jtbJornal.setModel(model);
        
        String [] titlesFu = {"ID","Nome","Data de nascimento","CPF",
            "Salario","Cargo"};
        String [] fieldsFu = {"funcionario.idFu","funcionario.nomeCompletoFu","funcionario.dataNascimentoFu",
            "funcionario.cpfFu","funcionario.salarioFu","tipoFuncionario.descricaoTipoFu"};
        String [] paramsFu = {"tipoFuncionario.idTipoFu=funcionario.idTipoFu"};
        String [][] sFu = dbInterface.view(fieldsFu, paramsFu, new String[]{"funcionario","tipoFuncionario"});
        
        model = new DefaultTableModel(sFu,titlesFu);
        jtbFuncionario.setModel(model);
        
        String [] fieldsExJo = {"exibicaoJornal.idPr","exibicaoJornal.idFu","exibicaoJornal.dataExJo",
            "exibicaoJornal.horaInicioExJo","exibicaoJornal.horaFimExJo","exibicaoJornal.ibopeExJo"
        };
        String [] titlesExJo = {"ID Jornal","ID Apresentador","Data",
            "Hora Início","Hora Fim","Ibope"
        };
        String [] paramsExJo = {
            "exibicaoJornal.idPr=jornal.idPr","exibicaoJornal.idFu=funcionario.idFu"
        };
        
        String [][] sExJo = dbInterface.view(fieldsExJo, paramsExJo, new String[]{"exibicaoJornal","jornal","funcionario"});
        
        model = new DefaultTableModel(sExJo,titlesExJo);
        jtbUpdate.setModel(model);
        
    }
    
    class ExJoAction implements ActionListener {
        
        /*
         * Controla os eventos de atualização
         */
        public void actionPerformed(ActionEvent e) {
            
            ArrayList<String> fields = new ArrayList<String>();
            
            if (jtbJornal.getSelectedRowCount() == 1) {
                fields.add("exibicaoJornal.idPr="+jtbJornal.getValueAt(jtbJornal.getSelectedRow(), 0));
            }
            
            if (jtbFuncionario.getSelectedRowCount() == 1) {
                fields.add("exibicaoJornal.idFu="+jtbFuncionario.getValueAt(jtbFuncionario.getSelectedRow(), 0));
            }
            
            if (jftxtIni.getText().compareTo("  :  ") != 0) {
                fields.add("exibicaoJornal.horaInicioExJo='"+jftxtIni.getText()+"'");
            }
            
            if (jftxtFim.getText().compareTo("  :  ") != 0) {
                fields.add("exibicaoJornal.horaFimExJo='"+jftxtFim.getText()+"'");
            }
            if (jftxtDate.getText().compareTo("  -  -    ") != 0) {
                fields.add("exibicaoJornal.dataExJo=TO_DATE('"+jftxtDate.getText()+"','DD-MM-YYYY')");
            }
            if (jtxtIbope.getText().trim().compareTo("") != 0) {
                fields.add("exibicaoJornal.ibopeExJo=TO_NUMBER('"+jtxtIbope.getText()+"')");
            }
            
            if (fields.size() > 0 && jtbUpdate.getSelectedRowCount() > 0) {
                String [] params = new String[4];
                String [] fieldsArray = new String[fields.size()];
                fields.toArray(fieldsArray);
                int [] rows = jtbUpdate.getSelectedRows();
                for ( int i = 0; i < rows.length; i++ ) {
                    try {
                        params[0] = "exibicaoJornal.idPr="+jtbUpdate.getValueAt(rows[i],0).toString();
                        params[1] = "exibicaoJornal.idFu="+jtbUpdate.getValueAt(rows[i],1).toString();
                        params[2] = "exibicaoJornal.dataExJo"
                                + "=TO_DATE('"+jtbUpdate.getValueAt(rows[i], 2).toString().substring(0,10) +
                                "','YYYY-MM-DD')";
                        params[3] = "exibicaoJornal.horaInicioExJo='"+jtbUpdate.getValueAt(rows[i], 3).toString()+"'";
                        dbInterface.update(fieldsArray, params,
                                new String[]{"exibicaoJornal"});
                    } catch (SQLException ex) {
                        frame.printException(ex);
                        JOptionPane.showMessageDialog(null, "Não foi possível "
                                + "atualizar os dados da " + rows[i] + "linha no banco.");
                    }
                }
            } else {
                JOptionPane.showMessageDialog(null, "Você deve selecionar os "
                        + "registros a serem modificados e inserir nos campos as modificações");
            }
            
            jtbUpdate.clearSelection();
            try {
                setupTable();
            } catch (SQLException ex) {
                frame.printException(ex);
            }
            
        }
    }

}
